package cn.huixh.blindbox.controller;

import cn.huixh.blindbox.annotation.TokenVerify;
import cn.huixh.blindbox.common.Common;
import cn.huixh.blindbox.common.ResultData;
import cn.huixh.blindbox.pojo.bo.AccountFileBO;
import cn.huixh.blindbox.pojo.dto.FileDTO;
import cn.huixh.blindbox.pojo.vo.FileVO;
import cn.huixh.blindbox.service.FileService;
import cn.huixh.blindbox.utils.JwtUtil;
import cn.huixh.blindbox.utils.ToolsUtil;
import cn.hutool.core.util.StrUtil;
import io.github.yedaxia.apidocs.ApiDoc;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.File;


/**
 * 文件接口
 *
 * @author huixh
 * @version 1.0
 * @date 2022/5/9 16:57
 */
@Slf4j
@RestController
@RequestMapping("/file")
@RequiredArgsConstructor
public class FileController extends BaseController {

    final FileService fileService;

    final JwtUtil jwtUtil;

    final ToolsUtil toolsUtil;

    /**
     * 图片上传
     * @param token   token 令牌
     * @param fileDTO fileDTO 图片信息
     * @return ResultData 图片信息
     */
    @TokenVerify
    @PostMapping("/upload")
    public ResultData< FileVO > upload(@RequestHeader(Common.TOKEN_KEY) String token,
                                       FileDTO fileDTO) {
        fileService.fileVerify(fileDTO.getFileBytes(), fileDTO.getMd5());
        String accountId = jwtUtil.getPayload("jti", token);
        AccountFileBO fileBO = AccountFileBO.of(fileDTO, accountId);
        fileService.uploadFile(fileBO);
        FileVO build = FileVO.builder().fileId(fileBO.getFileId())
                .url(StrUtil.format(toolsUtil.getFullUrl() + "/file/url/img/{}", fileBO.getFileId()))
                .build();
        return ResultData.success(build);
    }

    /**
     * 返回图片
     *
     * @param fileId   文件id
     * @param response 请求响应
     */
    @TokenVerify
    @ApiDoc(stringResult = "返回图像")
    @GetMapping(value = "/url/img/{fileId}", produces = MediaType.IMAGE_JPEG_VALUE)
    public void getResLink(@PathVariable String fileId, HttpServletResponse response) {
        File file = fileService.downloadFile(AccountFileBO.builder().fileId(fileId).build());
        responseWrite(response, file);
    }

    /**
     * 取消上传
     *
     * @return ResultData
     */
    @TokenVerify
    @DeleteMapping("/delete/{fileId}")
    public ResultData< String > delete(@RequestHeader(Common.TOKEN_KEY) String token, @PathVariable String fileId) {
        String accountId = jwtUtil.getPayload("jti", token);
        fileService.deleteFile(accountId, fileId);
        return ResultData.success("操作成功!");
    }

}
